package com.huitone.smspfm.core.filter;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.huitone.smspfm.logger.ExtLogger;

import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import com.bin.common.utils.DateTimeUtils;
import com.bin.common.utils.StringUtils;
import com.huitone.smspfm.context.utils.ContextUtils;
import com.huitone.smspfm.core.config.AppStaticConfigs;
import com.huitone.smspfm.core.constant.DealResult;
import com.huitone.smspfm.core.waterpipe.client.IGateLink;
import com.huitone.smspfm.core.waterpipe.client.impl.SimpleGateLink;
import com.huitone.smspfm.dao.oracle.BlackuseDao;
import com.huitone.smspfm.dao.oracle.entity.BlackUse;
import com.huitone.smspfm.dao.oracle.entity.GateDef;
import com.huitone.smspfm.redis.model.AppCanstant;
import com.huitone.smspfm.redis.model.SmsEntity;
import com.huitone.smspfm.redis.pipeline.PipelineOpts.ABExcuteCommands;

/**   
* @Title AddBlackUserFilterTask.java 
* @Package com.huitone.smspfm.core.filter 
* @Description TODO(用一句话描述该文件做什么) 
* @author ybliang   
* @date 2017年7月9日 下午3:23:14 
* @version V1.0   
*/
public class AddBlackUserFilterTask extends Thread {
	
	private ExtLogger logger = ExtLogger.create(AddBlackUserFilterTask.class);
	
	private String moduleName = "上行短信添加黑名单模块";
	
	private byte[] moduleNameB = AppStaticConfigs.stringRedisSerializer.serialize(moduleName); 
	
	private List<SmsEntity>[] results = null;
	
	private List<SmsEntity> entities = null;
	
	private int index = 0;
	
	public AddBlackUserFilterTask(List<SmsEntity> entities, List<SmsEntity>[] results, int index) {
		this.entities = entities;
		this.results = results;
		this.index = index;
	}

	@Override
	public void run() {
		
		if (entities == null) return;
		
		@SuppressWarnings("rawtypes")
		RedisScript<List> script = new DefaultRedisScript<List>(AppStaticConfigs.luaMoSmsBlackChecker, List.class);
		
		List<String> keys = new ArrayList<>();
		keys.add(AppStaticConfigs.iSMAffixZSet);
		
		List<String> params = new ArrayList<String>();
		for (int i = 0 ; i < entities.size() ; i ++) {
			// *:phoneNumber:*:sendport*:smcont
			SmsEntity entity = entities.get(i);
			
			String sp = null;
			
			IGateLink iGateLink = AppStaticConfigs.simpleGateLinkRegister.get(entity.getGateLinkId());
			if (iGateLink != null) {
				GateDef gateDef = ((SimpleGateLink)iGateLink).getGateDef();
				if (gateDef != null) {
					sp = gateDef.getSpNumber();
				}
			}
			
			StringBuffer buffer = new StringBuffer();
			buffer.append("*");
			buffer.append(":");
			buffer.append(entity.getUser());
			buffer.append(":");
			buffer.append("*");
			buffer.append(":");
			buffer.append(StringUtils.substringAfter(entity.getSendport(), sp) + "*");
			buffer.append(":");
			buffer.append(entity.getSmcont());
			
			params.add(buffer.toString());
		}
		
		List<String> result = AppStaticConfigs.scriptOpts2.getList(script, keys, params.toArray());
		
		List<String> remfromSMAffixZSet = new ArrayList<>();
		
		List<String> addblackcachelist = new ArrayList<String>();
		
		AppStaticConfigs.pipelineOpts3.save(new ABExcuteCommands() {

			@Override
			public void excute(RedisConnection connection) {
				
				List<SmsEntity> list = new ArrayList<>();
				
				for (int i = 0 ; i < entities.size() ; i ++) {
					
					SmsEntity entity = entities.get(i);
					
					if (entity.isExists()) {
						
						Map<byte[], byte[]> hashMap = new HashMap<>();
						hashMap.put(AppCanstant.SmsEntity.DealModuleName, moduleNameB);
						hashMap.put(AppCanstant.SmsEntity.SdealTime, AppStaticConfigs.stringRedisSerializer.serialize(DateTimeUtils.dateToStr2(new Date())));
						
						String phoneNum = StringUtils.phNumRem86(StringUtils.toString(entity.getUser()));
						String seqNum = StringUtils.toString(entity.getSequence()) + ":" + phoneNum;
						String smInfo = "SMInfo:" + seqNum;
						
						String string = result.get(i);
						if (!StringUtils.isEmpty(string)) {
							BlackuseDao dao = ContextUtils.getBean2(BlackuseDao.class);
							String[] split = string.split(":");
							String svrNode = StringUtils.toString(split[2]);
							String serviceCode = StringUtils.toString(split[3]);
							boolean inList = dao.isInList(svrNode, serviceCode, entity.getUser());
							if (!inList) {
								BlackUse blackUse = new BlackUse();
								blackUse.setRecId(StringUtils.uuid());
								blackUse.setSvrNode(svrNode);
								blackUse.setServiceCode(serviceCode);
								blackUse.setBlackUser(entity.getUser());
								blackUse.setStatus("1");
								blackUse.setInsertTime(new Date());
								blackUse.setDesc("由处理程序添加");
								int row = dao.insert(blackUse);
								if (row > 0) {
									// 加入到缓存列表当中
									String value = StringUtils.toString(blackUse.getSvrNode()) + ":" + StringUtils.toString(blackUse.getServiceCode()) + ":" + StringUtils.phNumRem86(StringUtils.toString(blackUse.getBlackUser()));
									//connection.zAdd(AppStaticConfigs.configBlackListZSetB, System.currentTimeMillis(), AppStaticConfigs.stringRedisSerializer.serialize(value));
									addblackcachelist.add(value);
								}
							}
							
							//connection.zRem(AppStaticConfigs.iSMAffixZSetB, AppStaticConfigs.stringRedisSerializer.serialize(string));
							remfromSMAffixZSet.add(string);
							connection.lPush(AppStaticConfigs.iSMMoEndListB, AppStaticConfigs.stringRedisSerializer.serialize(seqNum));
							
							logger.moprocc("用户["+entity.getUser()+"]加入黑名单,依据附加短信[序列号:手机号码:业务端编码:业务类型:扩展码:附加内容][" + string + "]对应上行短信[序列号:手机号码][" + seqNum + "]");
						
						} else {
							
							list.add(entity);
						}
						
						Date endTime = new Date();
						
						hashMap.put(AppCanstant.SmsEntity.EdealTime, AppStaticConfigs.stringRedisSerializer.serialize(DateTimeUtils.dateToStr2(endTime)));
						hashMap.put(AppCanstant.SmsEntity.DealResult, DealResult.RESULT0B);
						hashMap.put(AppCanstant.SmsEntity.DealResultDesc, DealResult.RESULT0_DESCB);
						
						connection.hMSet(AppStaticConfigs.stringRedisSerializer.serialize(smInfo), hashMap);
					}
				}
				
				results[index] = list;
			}
		});
		
		AppStaticConfigs.pipelineOpts2.save(new ABExcuteCommands() {

			@Override
			public void excute(RedisConnection connection) {
				
				for (String str:remfromSMAffixZSet) {
					if (!StringUtils.isEmpty(str)) {
						connection.zAdd(AppStaticConfigs.configBlackListZSetB, System.currentTimeMillis(), AppStaticConfigs.stringRedisSerializer.serialize(str));
					}
				}
				
				for (String str:addblackcachelist) {
					if (!StringUtils.isEmpty(str)) {
						connection.zRem(AppStaticConfigs.iSMAffixZSetB, AppStaticConfigs.stringRedisSerializer.serialize(str));
					}
				}
			}
		});
	}
}
